package com.coolgor.coldot.web.auth;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.coolgor.xutil.Net.HttpServletRequestUtil;
import com.coolgor.coldot.dto.auth.RoleExecution;
import com.coolgor.coldot.entity.auth.Role;
import com.coolgor.coldot.entity.auth.LocalUser;
import com.coolgor.coldot.entity.auth.LoginInfo;
import com.coolgor.coldot.enums.auth.LocalUserStateEnum;
import com.coolgor.coldot.enums.auth.LoginStateEnum;
import com.coolgor.coldot.enums.auth.RoleStateEnum;
import com.coolgor.coldot.service.auth.LocalUserService;
import com.coolgor.coldot.service.auth.LoginInfoService;
import com.coolgor.coldot.service.auth.RoleService;

/**
 * 登录认证控制器
 * web页面
 * 确认传入的用户名密码是否正确
 * @author CoolGor
 *
 */
@Controller
@RequestMapping("authlogin")
public class AuthLoginController {

	private static Logger log = LoggerFactory.getLogger(AuthLoginController.class);

	@Autowired
	private LocalUserService localUserService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private LoginInfoService loginInfoService;
	
	@RequestMapping(value="/login", method={RequestMethod.POST}, produces= {"application/json;charset=UTF-8"})
	@ResponseBody
	//@JsonIgnoreProperties(ignoreUnknown = true)//用ObjectMapper转换json对象时，忽略不存在的字段。
	public String doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		modelMap.put("success", false);			
		log.debug("Auth login post...");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String path = "/index.html";
		LocalUser localUser = null; 
		List<Role> roleList = null;
		Role loginRole = null;
		if (null==username || null==password) {
			path = "/logout.html";
			return "请从微信企业号或认证系统登录！";
		}else {
			//如果用户名和密码都不为null
			//制作登录日志信息
			LoginInfo loginInfo = new LoginInfo();
			loginInfo.setUsername(username);
			loginInfo.setLoginIP(HttpServletRequestUtil.getIP(request));
			loginInfo.setLoginWay(LoginStateEnum.WEB.getStateInfo());
			//根据username获取用户信息
			localUser = localUserService.getLocalUser(username);
			if (null == localUser) {
				//如果获取不到用户信息，即用户不存在
				path = "/logout.html";
				loginInfo.setNameCN("未知用户");
				loginInfo.setRemark("用户【"+username+"】不存在！");
			} else {
				//如果用户存在
				//在登陆信息种设置userid
				loginInfo.setUserID(localUser.getUserID());
				loginInfo.setNameCN(localUser.getNameCN());
				//判断用户名密码是否正确
				if (!password.equals(localUser.getPassword())) {
					//如果不正确
					loginInfo.setStatus(LoginStateEnum.DENIAL.getState());
					loginInfo.setStatusInfo(LoginStateEnum.DENIAL.getStateInfo());
					loginInfo.setRemark("[用户名密码错误]"+loginInfo.getRemark());
					//将本次登录日志写入数据库中
					loginInfoService.addLoginInfo(loginInfo);
					path = "/loginFalse.html";
					//如果用户名密码匹配成功
					//以下则开始判断用户状态
				} else if (localUser.getStatus()==LocalUserStateEnum.UNREGISTER.getState()) {
					//如果用户状态为未注册
					loginInfo.setStatus(LoginStateEnum.DENIAL.getState());
					loginInfo.setStatusInfo(LoginStateEnum.DENIAL.getStateInfo());
					loginInfo.setRemark("[本地用户未注册]"+loginInfo.getRemark());
					//将本次登录日志写入数据库中
					loginInfoService.addLoginInfo(loginInfo);
					return "用户未注册，登录失败！";
				}else if (localUser.getStatus()==LocalUserStateEnum.UNACTIVE.getState()) {
					//如果用户状态为未激活
					loginInfo.setStatus(LoginStateEnum.DENIAL.getState());
					loginInfo.setStatusInfo(LoginStateEnum.DENIAL.getStateInfo());
					loginInfo.setRemark("[本地用户未激活]"+loginInfo.getRemark());
					//将本次登录日志写入数据库中
					loginInfoService.addLoginInfo(loginInfo);
					return "用户未激活，登录失败！";
				}else if (localUser.getStatus()==LocalUserStateEnum.ACTIVE.getState()) {
					//如果用户状态为正常
					loginInfo.setStatus(LoginStateEnum.LOGINSUCCESS.getState());
					loginInfo.setStatusInfo(LoginStateEnum.LOGINSUCCESS.getStateInfo());
					//获取用户的角色
					RoleExecution roleExe = roleService.getRoleListByUser(localUser);
					if (roleExe.getState()==RoleStateEnum.SUCCESS.getState() && roleExe.getCount()>0) {
						//如果能正常获取用户的角色列表
						roleList = roleExe.getRoleList();
						loginRole = roleList.get(0);
						loginInfo.setLoginRoleId(loginRole.getRoleID());
						loginInfo.setLoginRoleName(loginRole.getRoleName());
						modelMap.put("success", true);	
					} else {
						//如果用户角色分配不正确，或者该用户未分配角色，拒绝登录
						loginInfo.setStatus(LoginStateEnum.DENIAL.getState());
						loginInfo.setStatusInfo(LoginStateEnum.DENIAL.getStateInfo());
						loginInfo.setRemark("[用户角色异常]"+loginInfo.getRemark());
					}
				}else if (localUser.getStatus()==LocalUserStateEnum.DENIAL.getState()) {
					//如果用户状态为禁用
					loginInfo.setStatus(LoginStateEnum.DENIAL.getState());
					loginInfo.setStatusInfo(LoginStateEnum.DENIAL.getStateInfo());
					loginInfo.setRemark("[当前用户已禁用]"+loginInfo.getRemark());
					//将本次登录日志写入数据库中
					loginInfoService.addLoginInfo(loginInfo);
					return "当前用户已禁用，登录失败！";
				}
				//将本次登录日志写入数据库中
				loginInfoService.addLoginInfo(loginInfo);
				
			}
		}		
		//将当前用户信息推入session
		if (null!=localUser && (Boolean)modelMap.get("success")==true) {
			request.getSession().setAttribute("login_user",localUser);
			if (null!=localUser.getHomepage() && !"".equals(localUser.getHomepage())) {
				path = localUser.getHomepage();
			} else {
				path = "/Main.html";
			}
			modelMap.put("local_user", localUser);
		}
		if (null!=roleList) {
			request.getSession().setAttribute("role_list",roleList);
			modelMap.put("role_list", roleList);
		}	
		if (null!=loginRole) {
			request.getSession().setAttribute("login_role",loginRole);
			modelMap.put("login_role", loginRole);
		}	
		response.sendRedirect(request.getContextPath() + path);	
		return modelMap.toString();
	}
	
	
	@RequestMapping(value="/logout", method={RequestMethod.GET}, produces= {"application/json;charset=UTF-8"})
	@ResponseBody
	//@JsonIgnoreProperties(ignoreUnknown = true)//用ObjectMapper转换json对象时，忽略不存在的字段。
	public String doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String path = "/logout.html";
		request.getSession().removeAttribute("login_user");
		request.getSession().removeAttribute("role_list");
		request.getSession().removeAttribute("login_role");
		response.sendRedirect(request.getContextPath() + path);	
		return null;
	}
}
